package com.imooc.searchcountdown;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 使用count down latch 问题是没有时间控制
 * @author ChangLiang
 * @date 2019/3/5
 */
public class App3 {

    private static Integer corePoolSize = 4;

    private static CountDownLatch countDownLatch;

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        countDownLatch = new CountDownLatch(4);

        long start = System.currentTimeMillis();

        EsService esService = new EsService();

        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("request-pool-%d").build();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                10,
                0L,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(20),
                threadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );
        threadPoolExecutor.execute(new QueryThread(countDownLatch,esService,"searchQueryItems",new Class<?>[]{String.class},new
                Object[]{"changliang"},list));
        threadPoolExecutor.execute(new QueryThread(countDownLatch,esService,"searchQueryGuides",new Class<?>[]{String.class},new
                Object[]{"changliang"},list));
        threadPoolExecutor.execute(new QueryThread(countDownLatch,esService,"getApplications",new Class<?>[]{String.class},new
                Object[]{"changliang"},list));
        threadPoolExecutor.execute(new QueryThread(countDownLatch,esService,"getAppointItems",new Class<?>[]{String.class},new
                Object[]{"changliang"},list));

        // 等待线程执行完毕
        try {

            countDownLatch.await();

            long end = System.currentTimeMillis();

            System.out.println((end - start));
            System.out.println(list);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            threadPoolExecutor.shutdown();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
